package com.quectel.util.kit;

import cn.hutool.crypto.asymmetric.AsymmetricAlgorithm;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.quectel.util.ex.common.DecodeException;
import com.quectel.util.ex.common.EncodeException;

import java.util.Base64;

/**
 * id帮助类
 *
 * @author: cl
 * @date: 2020-06-22 14:41:00
 */
public class IdKit {


    /**
     * 根据私钥加密字符串
     *
     * @param data       数据
     * @param privateKey 私钥的base64
     * @return 返回被加密的字符串 url类型base64编码
     */
    public static String encryptByPrivateKey(String data, String privateKey) {
        try {
            RSA rsa = new RSA(AsymmetricAlgorithm.RSA.getValue(), privateKey, null);
            return Base64.getUrlEncoder().encodeToString(rsa.encrypt(data, KeyType.PrivateKey)).replace("=", "$");
        } catch (Exception e) {
            throw new EncodeException(e);
        }
    }

    /**
     * 根据公钥解密
     *
     * @param data      公钥加密的url类型Base64字符传
     * @param publicKey 公钥的base64
     * @return 原始字符传
     */
    public static String decryptByPublicKey(String data, String publicKey) {
        try {

            RSA rsa = new RSA(AsymmetricAlgorithm.RSA.getValue(), null, publicKey);
            return new String(rsa.decrypt(Base64.getUrlDecoder().decode(data.replace("$", "=")), KeyType.PublicKey));
        } catch (Exception e) {
            throw new DecodeException(e);
        }
    }


}
